import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
import execjs
import requests
from lxml import etree


class BwZy:
    def __init__(self):
        # 首页地址
        self.indexUrl = 'https://qiye.obei.com.cn/web-zone/bwzy/procurement.html'
        # 数据地址
        self.dataUrl = 'https://qiye.obei.com.cn/web-zone/api/sys/zone/getPurchaseList'
        self.cookie = {}

    # 请求函数
    def get_request(self, method=None, url=None, headers=None, data=None, cookies=None):
        if method == 'GET':
            try:
                response = requests.get(url=url, headers=headers, cookies=cookies)
                response.encoding = response.apparent_encoding
                return response
            except Exception as e:
                print('GET请求数据失败', e)
        elif method == 'POST':
            try:
                response = requests.post(url=url, headers=headers, json=data, cookies=cookies)
                response.raise_for_status()
                response.encoding = response.apparent_encoding
                return response.json()
            except Exception as e:
                print('POST请求数据失败', e)
        else:
            print('请求方式错误！！！')

    # 第一次请求首页
    def one_index(self):
        header = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "connection": "keep-alive",
            "host": "qiye.obei.com.cn",
            "pragma": "no-cache",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0"
        }
        response = self.get_request(method='GET', url=self.indexUrl, headers=header)
        # 解析td、js、content
        response = etree.HTML(response.text)
        content = response.xpath('//meta[2]/@content')[0]
        td_code = response.xpath('//script[1]/text()')[0]
        js_url = 'https://qiye.obei.com.cn' + response.xpath('//script[2]/@src')[0]
        # 获取外联js
        js_code = self.get_request(method='GET', url=js_url).text
        self.get_cookie(content, td_code, js_code)

    # 获取cookie
    def get_cookie(self, content, td_code, js_code):
        js_cook = open('宝武资源.js', 'r', encoding='utf-8').read().replace('"content1"', content).replace('"td_code"', td_code).replace('"fun_code"', js_code)
        with open('js_cook.js', 'w', encoding='utf-8') as f:
            f.write(js_cook)
        js = execjs.compile(js_cook)
        js_cookie = js.call('get_cookie').split('P=')[1]
        self.cookie['ENVTGhxsh01MP'] = js_cookie

    def two_index(self):
        header = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "connection": "keep-alive",
            "host": "qiye.obei.com.cn",
            "pragma": "no-cache",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0"
        }
        response = self.get_request(method='GET', url=self.indexUrl, headers=header, cookies=self.cookie)
        self.cookie['csrfToken'] = response.cookies.get('csrfToken')

    # 获取数据
    def get_data(self, page):
        header = {
            "accept": "application/json, text/plain, */*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-length": "114",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://qiye.obei.com.cn",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://qiye.obei.com.cn/web-zone/bwzy/procurement.html",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "traceparent": "00-738a23251490ee5f08debf237803e18c-08debf237803e18c-01",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0",
            "x-csrf-token": ""
        }
        header['x-csrf-token'] = self.cookie['csrfToken']
        data = {
            "code": "bwzy",
            "noticeType": "1",
            "pageFlag": "addSelect",
            "pageNum": page,
            "pageSize": 10,
            "sidx": "issueDate",
            "sord": "desc"
        }
        response = self.get_request(method='POST', url=self.dataUrl, headers=header, cookies=self.cookie, data=data)
        self.parse_data(response)

    def parse_data(self, data):
        for info in data['data']:
            title = info['title']
            issueDate = info['issueDate']
            quotationEndDate = info['quotationEndDate']
            rfqMethod = info['rfqMethod']
            if rfqMethod == 'RAQ':
                rfqMethod = '询比价'
            else:
                rfqMethod = '综合比价'
            print(title, rfqMethod, issueDate, quotationEndDate)


    def mian(self):
        self.one_index()
        self.two_index()
        for page in range(1, 6):
            js_cookie = execjs.compile(open('js_cook.js', 'r', encoding='utf-8').read())
            self.cookie['ENVTGhxsh01MP'] = js_cookie.call('get_cookie').split('P=')[1]
            self.get_data(page)


if __name__ == '__main__':
    bwzyy = BwZy()
    bwzyy.mian()
